<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="20%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { addRootMenu, addItemMenu, updateMenu } from '@/api/demo/roule';
  import { getMenuList } from '@/api/demo/system';

  defineOptions({ name: 'MenuDrawer' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const isSubMenu = ref(false);
  const permissionId = ref(null);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue }] =
    useForm({
      labelWidth: 100,
      schemas: formSchema,
      showActionButtonGroup: false,
      baseColProps: { lg: 24, md: 24 },
    });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    isSubMenu.value = !!data?.isSubMenu;
    permissionId.value = data?.record?.permissionId || null;
    console.log(permissionId.value);
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
    // const treeData = await getMenuList();
    // updateSchema({
    //   field: 'parentMenu',
    //   componentProps: { treeData },
    // });
  });

  const getTitle = computed(() => {
    if (unref(isSubMenu)) {
      return '添加子目录';
    } else if (!unref(isUpdate)) {
      return '新增菜单';
    } else {
      return '编辑菜单';
    }
  });

  async function handleSubmit() {
    let params = { ...getFieldsValue() };
    params.meta = {
      title: params.title,
      icon: 'ion:grid-outline',
      orderNo: params.orderNo,
    };
    console.log(params);
    try {
      //添加子目录

      if (isUpdate.value) {
        // 编辑菜单
        params.permissionId = permissionId.value;
        const values = await updateMenu(params);
        closeDrawer();
        emit('success');
      } else if (isSubMenu.value) {
        // 添加子目录
        params.parentId = permissionId.value;
        const values = await addItemMenu(params);
        closeDrawer();
        emit('success');
      } else {
        // 新增菜单
        const values = await addRootMenu(params);
        closeDrawer();
        emit('success');
      }
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
